<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import * as echarts from "echarts";
import api from "@/api";

// 定义响应式数据
const chartData = ref([]);
const loading = ref(false);

const chartRef = ref(null);
let chartInstance = null;



// 6. 封装初始化图表的函数（复用）
const initChart = (datas) => {
  if (chartInstance) chartInstance.dispose(); // 销毁旧实例
  chartInstance = echarts.init(chartRef.value);

  const option = {
    legend: {
      show: false,
    },
    tooltip: {
      trigger: "item",
      formatter: "{b} : {c} ({d}%)",
    },
    plotOptions: {
      pie: {
        borderRadius: 5,
        dataLabels: [
          {
            enabled: true,
            distance: "-30%",
            filter: {
              property: "percentage",
              operator: ">",
              value: 5,
            },
            format: "{point.y:.1f}%",
            style: {
              fontSize: "0.9em",
              textOutline: "none",
            },
          },
        ],
      },
    },
    series: [
      {
        name: "",
        label: {
          show: true,
          position: "inside",
          formatter: "{d}%",
          fontSize: 12,
          color: "#fff",
        },
        padAngle: 3,
        type: "pie",
        data: datas || props.data,
      },
    ],
  };
  chartInstance.setOption(option);
};

// 获取设备分类数据
const getEquipmentCategoryData = async () => {
  try {
    loading.value = true;
    const res = await api.apiDashboardAdminDashboardDataPost();


    if (res && res.data && res.data.equipment_category_dic) {
      const equipment_category_dic = res.data.equipment_category_dic;


      // 处理数据格式，将 {key, value} 转换为 {name, value}
      if (Array.isArray(equipment_category_dic) && equipment_category_dic.length > 0) {

        const formattedData = equipment_category_dic.map(item => ({
          name: item.key,
          value: item.value
        }));
        chartData.value = formattedData;
        initChart(formattedData);
      } else {

        console.warn('equipment_category_dic 数据为空或格式不正确');
        // 使用默认数据
        const defaultData = [
          { name: "默认分类", value: 100 }
        ];
        chartData.value = defaultData;
        initChart(defaultData);
      }
    }
  } catch (error) {
    console.error('获取设备分类数据失败:', error);
    // 使用默认数据
    const defaultData = [
      { name: "默认分类", value: 100 }
    ];
    chartData.value = defaultData;
    initChart(defaultData);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  // 组件挂载时获取数据并初始化图表
  getEquipmentCategoryData();

  // 响应式resize
  const handleResize = () => chartInstance && chartInstance.resize();
  window.addEventListener("resize", handleResize);
  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    chartInstance && chartInstance.dispose();
  });
});

// 监听 chartData 变化
watch(
  chartData,
  (newData) => {
    if (newData && newData.length > 0) {
      initChart(newData);
    }
  }
);
</script>

<style scoped>
.chart-container {
  width: 100%;
  /* 自适应父容器宽度 */
  height: 100%;
}
</style>
